<template>
  <div>
    <el-form
      ref="configForm"
      :model="configForm"
      label-width="180px">
      <el-form-item label="按通道顺序转发：">
        <el-switch v-model="configForm.forward"></el-switch>
      </el-form-item>

      <span v-if="configForm.forward">
        <el-row>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="addPassage">
              增加通道
            </el-button>
          </el-form-item>
        </el-row>
        <el-row
          v-for="(config, index) in configForm.forwardConfig"
          :key="index"
          :gutter="20">
          <el-col :span="10">
            <el-form-item
              :label="config.type == 1 ? '第' + (index + 1) + '通道：' : '备用通道'"
              :prop="'forwardConfig.' + index + '.productId'"
              :rules="{
                required: true,
                message: '请选择通道',
                trigger: 'blur',
              }">
              <resource-select
                v-model="config.productId"
                :action="productGetList"
                valueKey="id"
                :searchDefault="searchDefault"
                labelKey="product_search_field"></resource-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="4"
            v-if="config.type == 1">
            <el-form-item
              label="权重"
              label-width="60px">
              <el-input-number
                style="width: 100%"
                v-model="config.weight"
                :min="0"
                :max="100"
                :precision="0"
                :step="1"
                :controls="false"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="0px">
              {{ config.supplierName }}
              <el-button
                v-if="index > 0 && config.type == 1"
                type="danger"
                size="small"
                @click="removePassage(index)">
                移除通道
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </span>
      <el-row>
        <el-col :span="12">
          <el-form-item label="按运营商转发：">
            <el-switch v-model="configForm.operatorForward"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <span v-if="configForm.operatorForward">
        <el-row
          v-for="(operator, index) in configForm.forwardOperatorConfig"
          :key="index">
          <span v-if="operator.type == 'other'" >
            <el-col :span="12">
              <el-form-item
                :label="operator.name + '：'"
                prop="forwardCmcc">
                <resource-select
                  v-model="operator.productId"
                  :action="productGetList"
                  valueKey="id"
                  :searchDefault="searchDefault"
                  labelKey="product_search_field"></resource-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item
                label="单价"
                label-width="60px">
                <el-input-number
                  style="width: 100%"
                  v-model="operator.unit_price"
                  :min="0"
                  :precision="4"
                  :step="1"
                  :controls="false"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label-width="10px">
                {{ operator.supplierName }}
              </el-form-item>
            </el-col>
          </span>
          <span v-else>
            <el-row v-for="(channel, c_index) in operator.channels" :key="index+'_'+c_index">
              <el-col :span="10">
                <el-form-item
                  :label="operator.name+'第' + (c_index+1) +'：'"
                  prop="forwardCmcc">
                  <resource-select
                    v-model="channel.productId"
                    :action="productGetList"
                    valueKey="id"
                    :searchDefault="searchDefault"
                    labelKey="product_search_field"></resource-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item
                  label="单价"
                  label-width="60px">
                  <el-input-number
                    style="width: 100%"
                    v-model="channel.unit_price"
                    :min="0"
                    :precision="4"
                    :step="1"
                    :controls="false"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col
                :span="3">
                <el-form-item
                  label="权重"
                  label-width="60px">
                  <el-input-number
                    style="width: 100%"
                    v-model="channel.weight"
                    :min="0"
                    :max="100"
                    :precision="0"
                    :step="1"
                    :controls="false"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label-width="10px">
                  {{ channel.supplierName }}
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label-width="0px">
                  <el-button
                    v-if="c_index == 0"
                    type="primary"
                    size="small"
                    @click="addOperatePassage(operator)">
                    增加通道
                  </el-button>
                  <el-button
                    v-if="c_index > 0"
                    type="danger"
                    size="small"
                    @click="removeOperatePassage(operator, c_index)">
                    移除通道
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </span>
        </el-row>
      </span>
    </el-form>
  </div>
</template>
<script>
import { getList as productGetList, getProductDetail } from '@/api/product';
import ResourceSelect from '@/components/ResourceSelect/index';
import isObject from 'lodash/isObject';
export default {
  name: 'phoneCheck',
  props: {
    userProductDetail: {
      type: [Object],
      default: null,
    },
  },
  components: {
    ResourceSelect,
  },
  watch: {
    userProductDetail: {
      handler(value) {
        if (value.config) {
          this.$set(this, 'configForm', value.config);
        }
      },
      immediate: true,
    },
    'configForm.forward': {
      handler(value) {
        if (!value) {
          this.$set(this.configForm, 'forwardConfig', this.configBaseData);
        } else {
          if (this.configForm.operatorForward) {
            this.$set(this.configForm, 'operatorForward', false);
          }
        }
      },
      immediate: true,
    },
    'configForm.operatorForward': {
      handler(value) {
        if (!value) {
          this.$set(this.configForm, 'forwardOperatorConfig', this.operatorBaseData);
        } else {
          if (this.configForm.forward) {
            this.$set(this.configForm, 'forward', false);
          }
        }
      },
      immediate: true,
    },
    'configForm.forwardConfig': {
      handler(value) {
        this.configForm.forwardConfig.forEach(item => {
          if (item.productId) {
            getProductDetail({ id: item.productId }).then(res => {
              item.supplierName = res.data.supplier.name;
            });
          }
        });
      },
      deep: true,
      immediate: true,
    },
    'configForm.forwardOperatorConfig': {
      handler(value) {
        this.configForm.forwardOperatorConfig.forEach(item => {
          if( isObject(item.channels) ){
            item.channels.forEach(info => {
              if (info.productId) {
                getProductDetail({ id: info.productId }).then(res => {
                  info.supplierName = res.data.supplier.name;
                });
              }
            })
          }
        });
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      productGetList,
      searchDefault: {
        category_id: 7,
      },
      configForm: {
        forward: false,
        forwardConfig: this.configBaseData,
        operatorForward: false,
        forwardOperatorConfig: this.operatorBaseData,
      },
      configBaseData: [
        {
          productId: '',
          supplierName: '',
          weight: 0,
          type: 1,
        },
        {
          productId: '',
          supplierName: '',
          type: 2,
        },
      ],
      operatorBaseData: [
        {
          name: '移动通道',
          type: 'cmcc',
          channels:[
            {
              productId: '',
              supplierName: '',
              unit_price: 0.0,
              weight: 0,
            }
          ]
        },
        {
          name: '联通通道',
          type: 'cucc',
          channels:[
            {
              productId: '',
              supplierName: '',
              unit_price: 0.0,
              weight: 0,
            }
          ]
        },
        {
          name: '电信通道',
          type: 'ctcc',
          channels:[
            {
              productId: '',
              supplierName: '',
              unit_price: 0.0,
              weight: 0,
            }
          ]
        },
        {
          name: '备用通道',
          type: 'other',
          productId: '',
          supplierName: '',
          unit_price: 0.0,
        },
      ],
    };
  },
  methods: {
    getConfigValue() {
      if (!this.configForm.forward && !this.configForm.operatorForward) {
        return this.configForm;
      } else {
        let result = false;
        this.$refs.configForm.validate(valid => {
          if (valid) {
            if (this.configForm.forward) {
              let sumWithInitial = 0;
              this.configForm.forwardConfig.forEach(item => {
                if (item.type == 1) {
                  sumWithInitial += item.weight;
                }
              });
              if (sumWithInitial != 100) {
                this.$message.error('所有通道权重总计必须为100');
              } else {
                result = this.configForm;
              }
            } else if( this.configForm.operatorForward ){
              let sumWithInitial = {
                cmcc:0,
                cucc:0,
                ctcc:0
              };
              this.configForm.forwardOperatorConfig.forEach( item => {
                if(item.type != 'other'){
                  let operateTotal = item.channels.reduce(function( cur, acr){
                    return acr.weight + cur
                  }, 0)
                  sumWithInitial[item.type] = operateTotal
                }
              })
              if( sumWithInitial.cmcc != 100 || sumWithInitial.cucc != 100 || sumWithInitial.ctcc != 100 ){
                this.$message.error('所有通道权重总计必须为100');
              } else {
                result = this.configForm;
              }
            } else {
              result = this.configForm;
            }
          }
        });
        return result;
      }
    },
    showProductDetail(productId, label) {
      if (!productId) {
        this[label] = '';
      } else {
        getProductDetail({ id: productId }).then(res => {
          this[label] = res.data.supplier.name;
        });
      }
    },
    addPassage() {
      this.configForm.forwardConfig.splice(-1, 0, {
        productId: '',
        supplierName: '',
        weight: 0,
        type: 1,
      });
    },
    // 移除指定通道
    removePassage(index) {
      this.configForm.forwardConfig.splice(index, 1);
    },
    // 增加指定类型运营商通道
    addOperatePassage(operator) {
      let index = this.configForm.forwardOperatorConfig.findIndex( el => el.type == operator.type )
      this.configForm.forwardOperatorConfig[index].channels.push({
        productId: '',
        supplierName: '',
        unit_price: 0.0,
      });
    },
    // 移除指定运营商指定通道
    removeOperatePassage(operator,index){
      let findIndexNum = this.configForm.forwardOperatorConfig.findIndex( el => el.type == operator.type )
      this.configForm.forwardOperatorConfig[findIndexNum].channels.splice(index, 1);
    }
  },
};
</script>
